package booter

import (
	"encoding/json"
	"gluenet/pkg/apis"
	"gluenet/pkg/meta"
)

func BootIns(c *apis.StorageContext) {
	// TODO 调用agent接口启动
	var (
		err            error
		op             string
		scheduleResult *meta.ScheduleResults
		instance       *meta.Instance
	)
	c.Logger.Debugf("receive boot or stop an instance %v", instance)

	if scheduleResult, instance, op, err = decodeBootEvent(c.RpcContext.Data.Data); err != nil {
		c.Logger.Debugf("decode boot event error %v, op %v", err)
		return
	}

	//var cells = meta.DeCodeScheduleCells(scheduleResult.InstancesCells)
	smaps, err := meta.DeCodeScheduleMaps(scheduleResult.ScheduleMap)
	if err != nil {
		c.Logger.Debugf("decode schedule map %v", err)
		return
	}

	switch op {
	case apis.OpInstanceCreate:
		if err = runInstance(instance, smaps, c); err != nil {
			c.Logger.Errorf("run agent %v", err)
			return
		}
	case apis.OpInstanceDelete:
		if err = stopInstance(instance, smaps, c); err != nil {
			c.Logger.Errorf("stop agent %v", err)
			return
		}
	default:
		c.Logger.Errorf("unknown op %v", op)
		return
	}
}

func decodeBootEvent(data []byte) (*meta.ScheduleResults, *meta.Instance, string, error) {
	var req = apis.IEvent{}
	if err := json.Unmarshal(data, &req); err != nil {
		return nil, nil, "", err
	}

	bts1, _ := json.Marshal(req.Data.([]interface{})[0])
	var res = meta.ScheduleResults{}
	if err := json.Unmarshal(bts1, &res); err != nil {
		return nil, nil, "", err
	}

	var ins meta.Instance
	if err := json.Unmarshal([]byte(req.Data.([]interface{})[1].(string)), &ins); err != nil {
		return nil, nil, "", err
	}

	return &res, &ins, req.Data.([]interface{})[2].(string), nil
}
